package com.zhong.beautifulimageapp;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.Toolbar;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.zhong.beautifulimageapp.adapter.CommonFragmentAdapter;
import com.zhong.beautifulimageapp.fragments.UserCollectTopicsFragment;
import com.zhong.beautifulimageapp.fragments.UserRecentRepliesFragment;
import com.zhong.beautifulimageapp.fragments.UserRecentTopicsFragment;
import com.zhong.beautifulimageapp.model.CollectTopicsEventBusMessage;
import com.zhong.beautifulimageapp.model.CommonVariable;
import com.zhong.beautifulimageapp.model.RecentRepliesEventBusMessage;
import com.zhong.beautifulimageapp.model.RecentTopicsEventBusMessage;
import com.zhong.beautifulimageapp.model.TopicBriefList;
import com.zhong.beautifulimageapp.model.UserAfterLoginInfo;
import com.zhong.beautifulimageapp.model.UserDetailInfo;
import com.zhong.beautifulimageapp.network.GetContentFromNetwork;
import com.zhong.beautifulimageapp.utils.BaseFragments;

import org.greenrobot.eventbus.EventBus;
import org.joda.time.DateTime;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class MyActivity extends BaseActivity {

    @BindView(R.id.MyActivity_header_userIcon)
    ImageView mMyActivityHeaderUserIcon;
    @BindView(R.id.MyActivity_header_userLoginName)
    TextView mMyActivityHeaderUserLoginName;
    @BindView(R.id.MyActivity_header_user_GitHub)
    TextView mMyActivityHeaderUserGitHub;
    @BindView(R.id.MyActivity_header_user_register_time)
    TextView mMyActivityHeaderUserRegisterTime;
    @BindView(R.id.MyActivity_header_user_score)
    TextView mMyActivityHeaderUserScore;
    @BindView(R.id.MyActivity_header_goBack)
    ImageView mMyActivityHeaderGoBack;
    @BindView(R.id.MyActivity_header_toUserGitHub)
    ImageView mMyActivityHeaderToUserGitHub;
    @BindView(R.id.MyActivity_header_toolbar)
    Toolbar mMyActivityHeaderToolbar;
    @BindView(R.id.MyActivity_header_table)
    TabLayout mMyActivityHeaderTable;
    @BindView(R.id.MyActivity_ViewPager)
    ViewPager mMyActivityViewPager;
    private UserRecentRepliesFragment mUserRecentRepliesFragment;
    private UserRecentTopicsFragment mUserRecentTopicsFragment;
    private UserCollectTopicsFragment mUserCollectTopicsFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);
        ButterKnife.bind(this);
        initView();
        getDataFromNet();
    }

    private void initView() {
        setSupportActionBar(mMyActivityHeaderToolbar);
        List<BaseFragments> baseFragmentses = new ArrayList<>();
        mUserRecentRepliesFragment = new UserRecentRepliesFragment();
        baseFragmentses.add(mUserRecentRepliesFragment);
        mUserRecentTopicsFragment = new UserRecentTopicsFragment();
        baseFragmentses.add(mUserRecentTopicsFragment);
        mUserCollectTopicsFragment = new UserCollectTopicsFragment();
        baseFragmentses.add(mUserCollectTopicsFragment);
        CommonFragmentAdapter adapter = new CommonFragmentAdapter(getSupportFragmentManager(), baseFragmentses);
        mMyActivityViewPager.setAdapter(adapter);
        mMyActivityViewPager.setOffscreenPageLimit(2);
        mMyActivityHeaderTable.setupWithViewPager(mMyActivityViewPager);
    }

    /**
     * 解决从其他人的个人信息界面返回时
     * ListView中的item复用造成数据错乱问题
     */
    @Override
    protected void onStart() {
        super.onStart();
        getDataFromNet();
    }

    public void getDataFromNet() {
        Intent intent = getIntent();
        String loginName;
        if (intent.hasExtra("loginName")) {
            loginName = intent.getStringExtra("loginName");
        } else {
            UserAfterLoginInfo info = new UserAfterLoginInfo();
            getTheUserAfterLoginInfo(info);
            loginName = info.getLoginName();
        }
        if (!loginName.equals("")) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(CommonVariable.baseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();

            GetContentFromNetwork network = retrofit.create(GetContentFromNetwork.class);
            //获取用户详细信息
            network.getUserDetailInfo(loginName)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<UserDetailInfo>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull UserDetailInfo info) {
                            if (!info.isSuccess()) {
                                Toast.makeText(MyActivity.this, "服务出错", Toast.LENGTH_SHORT).show();
                            } else {
                                Glide.with(MyActivity.this)
                                        .load(info.getData().getAvatar_url())
                                        .asBitmap()
                                        .placeholder(R.mipmap.app)
                                        .centerCrop()
                                        .into(new BitmapImageViewTarget(mMyActivityHeaderUserIcon) {
                                            @Override
                                            protected void setResource(Bitmap resource) {
                                                RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getResources(), resource);
                                                drawable.setCircular(true);
                                                mMyActivityHeaderUserIcon.setImageDrawable(drawable);
                                            }
                                        });
                                mMyActivityHeaderUserLoginName.setText(info.getData().getLoginname());
                                mMyActivityHeaderUserGitHub.setText(info.getData().getGithubUsername() + "@github.com");
                                DateTime time = new DateTime(info.getData().getCreate_at());
                                String s = "注册时间：" + time.toString("yyyy-MM-dd");
                                mMyActivityHeaderUserRegisterTime.setText(s);
                                mMyActivityHeaderUserScore.setText("积分：" + info.getData().getScore());
                                RecentRepliesEventBusMessage messageReplies = new RecentRepliesEventBusMessage();
                                messageReplies.setRepliesBeen(info.getData().getRecent_replies());
                                RecentTopicsEventBusMessage messageTopics = new RecentTopicsEventBusMessage();
                                messageTopics.setTopicsBeen(info.getData().getRecent_topics());
                                EventBus.getDefault().post(messageReplies);
                                EventBus.getDefault().post(messageTopics);
//                                Bundle RepliesDataBundle = new Bundle();
//                                RepliesDataBundle.putParcelable("RepliesData", (Parcelable) info.getData().getRecent_replies());
//                                mUserRecentRepliesFragment.setArguments(RepliesDataBundle);
//                                Bundle RepliesTopicDataBundle = new Bundle();
//                                RepliesDataBundle.putParcelable("RepliesTopicData", (Parcelable) info.getData().getRecent_topics());
//                                mUserRecentTopicsFragment.setArguments(RepliesTopicDataBundle);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            Toast.makeText(MyActivity.this, "网络出错", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
            //获取用户收藏的话题
            network.getUserCollectTopic(loginName)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<TopicBriefList>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {

                        }

                        @Override
                        public void onNext(@NonNull TopicBriefList list) {
                            if (!list.isSuccess()) {
                                Toast.makeText(MyActivity.this, "服务出错", Toast.LENGTH_SHORT).show();
                            } else {
                                CollectTopicsEventBusMessage messageCollect = new CollectTopicsEventBusMessage();
                                messageCollect.setItems(list.getData());
                                EventBus.getDefault().post(messageCollect);
//                                Bundle CollectTopicData = new Bundle();
//                                CollectTopicData.putParcelable("CollectTopicData", (Parcelable) list.getData());
//                                mUserCollectTopicsFragment.setArguments(CollectTopicData);
                            }
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            Toast.makeText(MyActivity.this, "网络出错", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }
    }

    @OnClick(R.id.MyActivity_header_goBack)
    public void goBack() {
        finish();
    }
}
